﻿using System;
using System.Text;

namespace ZilLion.Service.Core.Snowflake
{
    public class SnoWorKer: IdWorker
    {

        private static readonly char[] _rule = new char[] {'0','1','2','3','4','5','6','7','8','9',
                              'A','B','C','D','E','F','G','H','J','K',
                              'L','M','N','P','Q','R','S','T','U','V',
                              'W','X','Y','Z',};


        public SnoWorKer(long workerId,  long sequence = 0) : base(workerId,  sequence)
        {
        }


        public virtual string GetNewSno()
        {
            //10位长的34进制数据可对应0~2064377754059776，而50位的2进制是0~1125899906842623
            return ConverttoRadix34Str(base.NextId(),10); /*id.ToString("x8");*/
        }

        private static string ConverttoRadix34Str(long num, int len)
        {
            if (num < 0 | num >= Math.Pow(34, len))
            {
                throw new ArgumentException(String.Format("内部错误。（num={0}）", num));
            }
            var sb = new StringBuilder();
            for (int i = 1; i <= len; i++)
            {
                sb.Insert(0, _rule[num % 34]);
                num /= 34;
            }
            return sb.ToString();
        }
    }
}